package com.xtravel.common.widget;

import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.WindowManager;
import android.widget.GridView;
import android.widget.ListAdapter;

public class NoScrollGridView extends GridView {
    public NoScrollGridView(Context context) {
        super(context);

    }

    public NoScrollGridView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, expandSpec);
    }

    @Override
    public void setAdapter(ListAdapter adapter) {
        super.setAdapter(adapter);

        DisplayMetrics dm = new DisplayMetrics();
        ((Activity) getContext()).getWindowManager().getDefaultDisplay().getMetrics(dm);

        android.view.ViewGroup.LayoutParams params = getLayoutParams();

        WindowManager wm = ((Activity) getContext()).getWindowManager();
        int width = wm.getDefaultDisplay().getWidth();
        int imgWidth = (int) (width - ((32) * dm.density)) / 3;

        // params.width = (int) ((adapter.getCount() == 4 ? (imgWidth * 2) : (imgWidth * 3)));

        int numColumns = adapter.getCount() == 4 ? 2 : 3;
        params.width = (int) (imgWidth + 4 * dm.density) * numColumns;
        params.height = LayoutParams.WRAP_CONTENT;
        setNumColumns(numColumns);

        setLayoutParams(params);
    }

}